import { useEffect, useState } from "react";
import { Link } from "react-router-dom";

export default function Home() {
  const [posts , setPosts] = useState([]);
  const getPosts = async () => {
    const res = await fetch('api/posts');
    const data = await res.json();
    
    res.ok && setPosts(data.data);
    
  };
  useEffect(() => {
    getPosts();
  },[])
  return (
  <>
    <h1 className="title">
      最新文章{posts.length>0? `(${posts.length})`:''}
  </h1>
  {posts.length>0?posts.map((post,index)=>(
    <div key={index} className="mb-4 p-4 border border-gray-300 rounded-md">
      <div className="mb-2 flex items-start justify-between">
        <div>
          <h2 className="font-bold text-lg">{post.title}</h2>
          <small>{new Date(post.created_at).toLocaleTimeString()}</small>
          <small>{'作者：'+post.user.name}</small>
        </div>
        <Link to={`/posts/${post.id}`} className="bg-blue-500 text-white
        text-sm rounded-lg px-3 py-1
        ">阅读全文</Link>
      </div>
      <p>{post.body}</p>
       </div>
  )):(<div>暂无文章</div>)}
  </>
  )
}